<template>
	<div>
		<div class="choice-question" :class="{'edit': type==='edit'}">
			<span class="title">关联试题:</span>
			<span
				class=" f-12 text-overflow-1"
				:class="{
					'question-name': showSearch === false,
					'question-name-line': showSearch
				}"
			>
				<ve-parse :article="questionName" />
			</span>
			<span class="num f-12">{{ questionNumStr }}</span>
			<el-button v-if="questionList.length" type="text" @click="onLookQuestion">查看</el-button>
			<el-button
				v-if="type==='add'"
				class="theme_font_color theme-border-color"
				size="mini"
				@click="onChoiceQuestion"
			>
				选择试题
			</el-button>
			<el-button
				v-if="type==='edit'"
				type="text"
				size="mini"
				icon="el-icon-edit"
				@click="onChoiceQuestion"
			>
				重新选择
			</el-button>
			<span v-if="showSearch">&ensp;或&ensp;</span>
			<el-popover
				:width="questionPopoverWidth"
				trigger="manual"
				style="flex: 1;"
				ref="popover"
				popper-class="question-popover"
				v-if="showSearch"
			>
				<ul v-if="questionSearchList.length > 0" class="el-select-dropdown__list">
					<li
						@click="handleQuestionClick(item)"
						class="el-select-dropdown__item"
						v-for="(item, index) in questionSearchList"
						:key="item.questionStemId"
						:class="{
							selected: item.isFocus,
							hover: item.isHover
						}"
						:tabIndex="index + 100"
						:title="item.content"
					>
						{{ item.content }}
					</li>
				</ul>
				<p v-else-if="questionSearchList.length <= 0 && !isSearching" class="el-button--text" style="padding: 10px 8px;">当前视频的科目下，找不到符合条件的试题，请更换关键词重试</p>
				<el-input
					v-model="searchTxt"
					placeholder="输入试题题干，回车，会自动关联"
					maxlength="100"
					show-word-limit
					style="flex: 1;min-width: 400px;"
					slot="reference"
					@keyup.enter.native="handleSearchEnter"
					ref="searchInput"
					class="question-search-input"
					clearable
				>
					<img
						slot="suffix"
						src="../../../../../assets/images/enter.png"
						width="17"
						height="17"
						style="vertical-align:middle;"
					>
				</el-input>
			</el-popover>
		</div>
		<!-- 关联试题弹窗 -->
		<question-dialog
			ref="questionDialogRef"
			v-if="questionDialogData.isShow"
			:visibly.sync="questionDialogData.isShow"
			:resource-project-list="projectList"
			:default-data="questionList"
			:search-fom-data="type==='add'?searchFomData:null"
			@submit="onQuestionSubmit"
		/>
		<!-- 查看删除已关联试题弹窗 -->
		<question-delete-dialog
			v-if="questionDeleteDialogData.isShow"
			:visibly.sync="questionDeleteDialogData.isShow"
			:list="defaultData"
			:upper-deal="type==='edit'"
			@delete="handleDelete"
			@change="onQuestionChange"
		/>
	</div>
</template>
<script>
	import qbApi from "@rc/apis/qb/index.mjs";
	import coursewareApi from "@rc/apis/rc/courseware.mjs";
	import QuestionDialog from "../question-dialog/index.vue"; //选择知识点
	import QuestionDeleteDialog from "../question-delete-dialog/index.vue"; //选择知识点
	export default {
		name: "choice-question",
		props: {
			projectSubjectList: {
				type: Array,
				default: () => []
			},
			type: {
				type: String,
				default: "add"
			},
			resourceVideoDotId: {
				type: String,
				default: ""
			},
			projectIds: {
				type: Array,
				default: () => []
			},
			showSearch: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			projectSubjectList: {
				handler(res) {
					if (res && res.length) {
						this.transformId();
					}
				},
				immediate: true
			},
			projectIds: {
				handler(val) {
					if (val && val.length) {
						this.questionIdList = val;
						this.queryQuestionListByIds();
					}
				},
				immediate: true
			}
		},
		data() {
			return {
				questionList: [], //已选择的试题列表
				questionDialogData: {
					isShow: false
				},
				questionDeleteDialogData: {
					isShow: false
				},
				projectList: [], //项目列表
				questionIdList: [],
				questionDeleteList: [],
				defaultData: [],
				searchFomData: {},
				typeList: {
					S: "【单选题】",
					M: "【多选题】",
					J: "【判断题】",
					F: "【填空题】",
					O: "【简答题】",
					I: "【不定项选择】",
					BC: "【选词填空】",
					CF: "【完形填空】",
					L: "【听力题】",
					A: "【材料分析】",
					C: "【配伍题】"
				},
				searchTxt: '',
				questionSearchList: [],
				questionPopoverWidth: 580,
				isSearching: false,
			};
		},
		components: {
			QuestionDialog,
			QuestionDeleteDialog
		},
		computed: {
			questionName() {
				if (this.questionList.length) {
					const question = this.questionList[0];
					let questionName = "";
					let title = "";
					if (question.questionstemDetail) {
						//组合题
						title = question.questionList[0].questionDetail.questionContent;
						const type = question.questionstemDetail.questionstemType;
						questionName = this.typeList[type] + JSON.parse(title).title;
					} else {
						title = question.questionDetail.questionContent;
						const type = question.questionDetail.questionType;
						questionName = this.typeList[type] + JSON.parse(title).title;
					}
					return questionName;
				}
				return "--";
			},
			questionNumStr() {
				if (this.questionIdList.length && this.questionIdList.length !== 1) {
					return `+${this.questionIdList.length - 1}`;
				}
				return "";
			}
		},
		mounted() {
			window.addEventListener('click', this.handleWindowClick);
			this.getPopoverWidth();
		},
		beforeDestroy() {
			window.removeEventListener('click', this.handleWindowClick);
		},
		methods: {
			//删除后更新questionList
			onQuestionChange(resultArr, list) {
				this.questionIdList = list.map((question) => this.getQuestionRowKeys(question));
				this.questionList = list;
				this.defaultData = resultArr;
			},
			//根据试题id查询试题列表
			queryQuestionListByIds(callback) {
				if (!this.questionIdList.length) {
					return;
				}
				qbApi.queryQuestionListByIds({
					data: {
						questionIds: this.questionIdList.toString(),
						pageIndex: 0,
						pageSize: 20
					},
					success: (res) => {
						let questionShowList = [];
						const result = JSON.parse(JSON.stringify(res.data));
						result.forEach((question, index) => {
							if (question.questionstemDetail.questionstemId) {
								question.qIndex = index + 1;
								questionShowList.push(question);
								question.questionList.forEach((subQuestion, sIndex) => {
									subQuestion.qIndex = index + 1 + "-" + (sIndex + 1);
									subQuestion.parentIndex = index;
									subQuestion.parentQuestionId = question.questionstemDetail.questionstemId;
									subQuestion.isSqLast = sIndex === question.questionList.length - 1; //是不是最后一道小题
									questionShowList.push(subQuestion);
								});
							} else {
								question.qIndex = index + 1;
								questionShowList.push(question);
							}
						});
						this.defaultData = questionShowList;
						this.questionDeleteList = questionShowList;
						this.questionList = questionShowList.filter((i1) => {
							return !(i1.questionstemDetail && i1.questionstemDetail.questionstemId);
						});
						this.questionIdList = this.questionList.map((question) => this.getQuestionRowKeys(question));
						callback && callback();
					}
				});
			},
			onChoiceQuestion() {
				if (!this.projectList.length) {
					this.$message.warning("当前课件关联的项目下，没有试题!");
					return;
				}
				const searchFomData = localStorage.getItem("searchFomData");
				this.searchFomData = searchFomData ? JSON.parse(searchFomData) : null;
				this.questionDialogData.isShow = true;
			},
			//试题筛选需要将基础数据项目科目转换为题库项目和科目
			transformId() {
				const projectIds = this.projectSubjectList.map((project) => project.projectId);
				let subjectList = [];
				this.projectSubjectList.forEach((project) => {
					subjectList.push(...project.subjectList);
				});
				const bdsubjectIds = subjectList.map((subject) => subject.subjectId);
				Http.callServices([
					{
						url: "qb/tpo/class/list/projectids", //项目id转换
						data: {
							projectIds: projectIds.toString()
						}
					},
					{
						url: "qb/business/subject/convert", // 科目id转换
						data: {
							bdsubjectIds
						}
					}
				]).success((projectData, subjectData) => {
					const qbProjectList = projectData.data;
					const qbSubjectList = subjectData.subjectInfos;

					let projectList = [];
					this.projectList = this.projectSubjectList.forEach((bdProject) => {
						const currentProject = qbProjectList.find((qbProject) => qbProject.projectId === bdProject.projectId);
						if (!currentProject) {
							//基础数据项目在题库没有查到
							return;
						}
						const currentSubjectList = qbSubjectList.filter((subject) => subject.classId === currentProject.classId);
						const subjectList = currentSubjectList.map((subject) => {
							return {
								subjectId: subject.subjectId,
								subjectName: subject.subjectName
							};
						});
						if (!subjectList.length) {
							//项目下的科目在题库中没有找到
							return;
						}
						projectList.push({
							projectId: currentProject.classId,
							projectName: currentProject.className,
							subjectList
						});
					});
					this.projectList = projectList;
				});
			},
			onQuestionSubmit(questionList) {
				console.warn('onQuestionSubmit', questionList);
				if (!questionList.length) {
					this.$message.warning("请选择试题");
					return;
				}
				if (questionList.length > 20) {
					this.$message.warning("最多可以关联20道试题");
					return;
				}

				if (this.type === "add") {
					this.questionIdList = questionList.map((question) => this.getQuestionRowKeys(question));
					this.queryQuestionListByIds();
					this.searchFormData = this.$refs.questionDialogRef.api_getSearchFormData();
					localStorage.setItem("searchFomData", JSON.stringify(this.searchFormData));
					this.questionList = questionList;
					this.questionDialogData.isShow = false;
					return;
				}
				if (this.type === "edit") {
					this.updateResourceVideoQuestion(questionList);
				}
			},
			handleDelete(arr) {
				const questionIdList = arr.map((question) => this.getQuestionRowKeys(question));
				this.questionIdList = questionIdList;
				coursewareApi.updateResourceVideoQuestion({
					data: {
						resourceVideoDotId: this.resourceVideoDotId,
						questionList: questionIdList
					},
					success: () => {
						//刷新视频
						this.$emit("update-success");
						this.$message.success("删除试题成功");
					}
				});
			},
			/**
			 * 更新关联的试题
			 */
			updateResourceVideoQuestion(questionList) {
				this.$confirm("确定更新关联试题吗？", "提示", {
					type: "warning"
				}).then(() => {
					const questionIdList = questionList.map((question) => this.getQuestionRowKeys(question));
					coursewareApi.updateResourceVideoQuestion({
						data: {
							resourceVideoDotId: this.resourceVideoDotId,
							questionList: questionIdList
						},
						success: () => {
							//刷新视频
							this.$emit("update-success");
							this.$message.success("更新试题成功");
							this.questionDialogData.isShow = false;
						}
					});
				});
			},
			onLookQuestion() {
				this.questionDeleteDialogData.isShow = true;
			},
			getQuestionRowKeys(question) {
				if (question.questionstemDetail && question.questionstemDetail.questionstemId) {
					//大题
					return question.questionstemDetail.questionstemId;
				} else if (question.questionstemDetail) {
					// 独立题型
					return question.questionList[0].questionDetail.questionId;
				} else {
					//大题下小题
					return question.questionDetail.questionId;
				}
			},
			/**
			 * 返回试题id数组
			 */
			api_getQuestionList() {
				return {
					questionIdList: this.questionIdList
				};
			},
			handleSearchEnter() {
				console.warn(this.projectList.map(({subjectList}) => subjectList).flat());
				this.isSearching = true;
				qbApi.queryQuestionListByContent({
					content: this.searchTxt,
					subjectIds: this.projectList.map(({subjectList}) => subjectList).flat().map(({ subjectId }) => subjectId),
				}).then(({ data = []}) => {
					const types = Object.entries(this.typeList);
					data.forEach((item, index) => {
						item.knowledgeName = item.knowledgeTitle;
						item.isFocus = index === 0;
						item.isHover = index === 0;
						const content = item.content.replaceAll('【图片】', '');
						const tye = content.substring(content.lastIndexOf('【') + 1, content.lastIndexOf('】')).replaceAll('题', '');
						const t = types.find((item) => {
							return item[1].includes(tye);
						});

						const questionType = t ? t[0] : '';
						item.questionDetail = {
							questionContent: JSON.stringify({
								title: item.content.substring(item.content.lastIndexOf('】') + 1),
							}),
							questionType: questionType,
							questionstemDetail: {
								questionstemId: item.questionStemId
							},
						};
					});
					this.questionSearchList.splice(0, this.questionSearchList.length, ...data);
					this.$nextTick(() => {
						const dmp = document.querySelector('.question-popover:nth-of-type(n+2)');
						if (dmp.isAddClickListener !== true) {
							dmp.isAddClickListener = true;
							dmp.addEventListener('keyup', (e) => {
								switch(e.keyCode) {
									case 40:
										{
											const it = this.questionSearchList.find(({ isFocus }) => isFocus);
											const idx = this.questionSearchList.findIndex(({ isFocus }) => isFocus);
											it && (it.isFocus = false);
											if (idx < this.questionSearchList.length - 1) {
												this.questionSearchList[idx + 1].isFocus = true;
											} else if (this.questionSearchList.length) {
												this.questionSearchList[0].isFocus = true;
											}
										}
										break;
									case 38:
										{
											const it = this.questionSearchList.find(({ isFocus }) => isFocus);
											const idx = this.questionSearchList.findIndex(({ isFocus }) => isFocus);
											it && (it.isFocus = false);
											if (idx > 0) {
												this.questionSearchList[idx - 1].isFocus = true;
											} else if (this.questionSearchList.length) {
												this.questionSearchList[this.questionSearchList.length - 1].isFocus = true;
											}
										}
										break;
									case 13:// enter
										{
											if (this.questionSearchList.length <= 0) {
												return;
											}
											this.$refs.popover.doClose();
											const it = this.questionSearchList.find(({ isFocus }) => isFocus);
											const ret = it.questions.every(({ questionId }) => this.questionIdList.includes(questionId));
											if (it && ret === false) {
												this.queryQuestionList(it.questions.map(({ questionId }) => questionId));
												this.$nextTick(this.getPopoverWidth);						
											}
											this.searchTxt = '';
											this.$refs.searchInput.focus();	
										}
										break;
								}
							});
						}
						this.$refs.searchInput.blur();
						dmp.focus();
					});
					this.$refs.popover.doShow();
				}).finally(() => {
					this.isSearching = false;
				});
			},
			handleQuestionClick(item) {
				this.$refs.popover.doClose();
				const ret = item.questions.every(({ questionId }) => this.questionIdList.includes(questionId));
				if (item && ret === false) {
					this.searchTxt = '';
					this.queryQuestionList(item.questions.map(({ questionId }) => questionId));
					this.$nextTick(this.getPopoverWidth);		
					this.$refs.searchInput.focus();					
				}
			},
			handleWindowClick() {
				this.$refs.popover && this.$refs.popover.doClose();
			},
			getPopoverWidth() {
				const dm = document.querySelector('.question-search-input');
				const style = getComputedStyle(dm);
				this.questionPopoverWidth = parseFloat(style.width);
			},
			queryQuestionList(ids) {
				qbApi.queryQuestionListByIds({
					data: {
						questionIds: ids.join(),
						pageIndex: 0,
                		pageSize: 100,
					},
					success: ({ data = [] }) => {
						console.warn(data);
						const questionShowList = [];
						const result = JSON.parse(JSON.stringify(data));
						result.forEach((question, index) => {
							if (question.questionstemDetail.questionstemId) {
								question.qIndex = index + 1;
								questionShowList.push(question);
								question.questionList.forEach((subQuestion, sIndex) => {
									subQuestion.qIndex = index + 1 + "-" + (sIndex + 1);
									subQuestion.parentIndex = index;
									subQuestion.parentQuestionId = question.questionstemDetail.questionstemId;
									subQuestion.isSqLast = sIndex === question.questionList.length - 1; //是不是最后一道小题
									questionShowList.push(subQuestion);
								});
							} else {
								question.qIndex = index + 1;
								questionShowList.push(question);
							}
						});
						this.defaultData.push(...questionShowList);
						this.questionDeleteList.push(...questionShowList);
						this.questionList.push(...questionShowList.filter((i1) => {
							return !(i1.questionstemDetail && i1.questionstemDetail.questionstemId);
						}));
						this.questionIdList = this.questionList.map((question) => this.getQuestionRowKeys(question));
					},
				});
			},
		}
	};
</script>
<style lang="less" scoped>
	.choice-question {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		line-height: 50px;

        .question-name{
			flex: 1;

            /deep/ img{
                max-height: 40px;
                max-width: 40px;
            }
        }

		.question-name-line{
            /deep/ img{
                max-height: 40px;
                max-width: 40px;
            }
        }

		&.edit {
			height: 40px;
			line-height: 40px;
		}
		.title {
			font-weight: bold;
			font-size: 14px;
			flex-shrink: 0;
			margin-right: 5px;
		}
		.f-12 {
			font-size: 12px;
		}
		.num {
			flex-shrink: 0;
		}
		.el-button {
			height: 32px !important;
			margin-left: 10px;
			&.edit {
				padding: 7px 8px;
			}
		}
	}
	.question-search-input /deep/ .el-input__inner {
		padding-right: 100px;
	}
</style>
<style lang="less">
	.question-popover {
		padding: 0;
	}
</style>
